import { FlexCiFeatureDefinition } from "../../types";
import logsets from 'logsets'; 
import { asyncExecShellScript, getCurrentPackageInfo, getPackageInfo, getProjectRootPath, installPackage } from "../../utils";
import fs from "fs-extra"
import path from "path"
import ejs from "ejs";

function renderComplate(complateFile:string,vars:Record<string,any>):string {
    const template = ejs.compile(String(fs.readFileSync(complateFile)));
    return template(vars)
}

export const docs:FlexCiFeatureDefinition =  {
    title:"项目文档(docsify)",
    install:async () => {
        const projectRoot = getProjectRootPath();
        const tasks = logsets.tasklist()
        // await tasks.run("安装{}",["docsify"],async () => {
        //     await installPackage("docsify",{type:"dev"});
        // }) 
        // await tasks.run("创建项目文档目录:{}",["./docs"],async () => {            
        //     if(!fs.existsSync(path.join(projectRoot, "docs"))){
        //         fs.mkdirSync("docs")
        //     }else{
        //         return "SKIP"
        //     }
        // }) 
        //"version": "conventional-changelog -p angular -i ./docs/CHANGELOG.md -s -r 0 && git add ./docs/CHANGELOG.md"
        // about

        const files=[
            {name:".nojekyll",content:""},
            {name:"_sidebar.md",content:"template://./sidebar.ejs"},
            {name:"_coverpage.md",content:"template://./coverpage.ejs"},
            {name:"index.html",content:"template://./index.ejs"},
            {name:"readme.md",content:"# 关于"},
            {name:"intro/get-started.md",content:"# 快速入门",title:"快速入门"},
            {name:"intro/install.md",content:"# 安装",title:"安装"},
            {name:"intro/changelog.md",content:"# 更新历史",title:"更新历史"},
            {name:"intro/question.md",content:"# 常见问题",title:"常见问题"},            
            {name:"guide/readme.md",content:"# 指南",title:"指南"}
        ] as {
            name:string
            content:string
            overwrite?:boolean
            title?:string
            vars?:Record<string,any>            // 传递给模板的额外变量
        }[]

        const docsPath = path.join(projectRoot,"docs")
        const currentPackage = getCurrentPackageInfo()
        for(let file of files){
            await tasks.run("生成{}",[file.name],async () => {               
                const filename = path.join(docsPath,file.name)
                const isExists = await fs.exists(filename)
                const isGenerate = !isExists || (isExists && file.overwrite)
                if(isGenerate){
                    let fileContent = file.content
                    if(file.content.startsWith("template://")){
                        let templateFile = file.content.substring(11)
                        if(!path.isAbsolute(templateFile)) templateFile=path.join(__dirname,templateFile)
                        fileContent = renderComplate(templateFile,{
                            package:currentPackage,
                            vars:file.vars || {}
                        })                        
                    }
                    fs.mkdirpSync(path.dirname(filename))
                    await fs.writeFile(filename,fileContent,{encoding: "utf8"})                    
                }
            }) 
        }            
        await tasks.run("配置{}命令来自动生成更新历史",["changelog"],async () => {
            await asyncExecShellScript(`npm pkg set scripts.version="npm changelog"`)
            await asyncExecShellScript(`npm pkg set scripts.changelog="conventional-changelog -p angular -i ./docs/intro/changelog.md -s -r 0 && git add ./docs/intro/changelog.md"`)                
        })  

    }
}